package com.zyl.blog.common.config;

import com.zyl.blog.common.handler.YamlMessageSource;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver;

import java.util.Locale;

/**
 * @version v1.0
 * @ProjectName: Personal_Blog_Server
 * @Package: com.zyl.blog.common.config
 * @ClassName: InternationalConfig
 * @Description:
 * @Author FinalFantasy
 * @Date 2025/9/9-15:38
 */
@Configuration
public class InternationalConfig {

    /**
     * 区域解析器（请求头判断语言，保持不变）
     * @return LocaleResolver
     */
    @Bean
    public LocaleResolver localeResolver() {
        AcceptHeaderLocaleResolver resolver = new AcceptHeaderLocaleResolver();
        resolver.setDefaultLocale(Locale.CHINA);
        return resolver;
    }

    /**
     * 消息源（使用修复后的YamlMessageSource，支持多模块）
     * @return MessageSource
     */
    @Bean
    public MessageSource messageSource() {
        YamlMessageSource messageSource = new YamlMessageSource(); // 之前定义的YAML支持类
        // 关键：指定所有模块的i18n消息路径（多个路径用逗号分隔）
        messageSource.setBasenames(
                "classpath:i18n/common",    // common模块的公共消息
                "classpath:i18n/auth",      // auth模块的消息
                "classpath:i18n/task",      // task模块的消息
                "classpath:i18n/file"       // file-processing模块的消息
        );
        messageSource.setDefaultEncoding("UTF-8");
        messageSource.setCacheSeconds(-1); // 开发环境不缓存
        return messageSource;
    }

    /**
     * 让JSR303校验（如@NotBlank）也使用国际化消息
     * @param messageSource 消息源
     * @return LocalValidatorFactoryBean
     */
    @Bean
    public LocalValidatorFactoryBean validator(MessageSource messageSource) {
        LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
        validator.setValidationMessageSource(messageSource);
        return validator;
    }
}